<template>
  <div class="container">
    <el-row>
      <el-col :span="12" :xs="0"></el-col>
      <el-col :span="12" :xs="24">
        <el-form class="login_box" :model="loginForm" :rules="ruleForm" ref="form">
          <h1>Hello</h1>
          <h2>硅谷甄选运营管理平台</h2>
          <el-form-item label="" size="large" prop="username">
            <el-input
              type="input"
              size="large"
              placeholder="请输入用户名"
              :prefix-icon="User"
              clearable
              v-model="loginForm.username"
              @change=""
            ></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              type="password"
              size="large"
              placeholder="请输入密码"
              :prefix-icon="Lock"
              show-password
              clearable
              v-model="loginForm.password"
              @change=""
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button class="login_btn" :loading="loading" type="primary" size="large" @click="login">登录</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { User, Lock } from '@element-plus/icons-vue'
import { reactive, ref, onMounted, onUnmounted } from 'vue'
import useUserStore from '@/store/modules/user'
import type { LoginForm } from '@/api/user/type'
import { UserApi } from '@/api/user'
import { useRoute, useRouter } from 'vue-router'
import { getTimeString } from '@/utils/date'
import { ElNotification, FormRules } from 'element-plus'
let userStore = useUserStore()
let $route = useRoute()
let $router = useRouter()

let loading = ref(false)

onMounted(() => {
  window.addEventListener('keydown', keyDown)
})

onUnmounted(() => {
  window.removeEventListener('keydown', keyDown, false)
})
// 收集表单数据
let loginForm: LoginForm = reactive({ username: '', password: '' })
const ruleForm = reactive<FormRules<LoginForm>>({
  username: [{ required: true, min: 5, max: 20, message: '用户名长度为5-10位', trigger: 'change' }],
  password: [{ required: true, min: 6, max: 20, message: '密码长度为6-20位', trigger: 'change' }]
})
// 获取form实例
const form = ref()
const login = async () => {
  try {
    await form.value.validate()
    loading.value = true
    const token = await UserApi.login(loginForm)
    userStore.setToken(token)
    let redirect: string = ($route.query?.redirect as string) || '/'
    $router.push({ path: redirect, replace: true })
    ElNotification({
      type: 'success',
      title: `Hi，${getTimeString()}好`,
      message: '欢迎登录甄选平台！'
    })
  } catch (_) {
  } finally {
    loading.value = false
  }
}

//点击回车键登录
const keyDown = (e: any) => {
  if (e.keyCode == 13 || e.keyCode == 100) {
    login()
  }
}
</script>

<style scoped lang="scss">
@import url('./index.scss');
</style>
